#! /usr/bin/env python3
"""
Basically, this module is simply wrap the functions of peewee,
but fulfils my limited requirements and provide more convenience.
"""
from model_person import Person
from peewee import DoesNotExist
import peewee


def add_a_person(**kw):
    """Create a record(Person instance) with the given parameter, and then save it. If the
     necessary parameter is not given, or the unique field is existed, a
     exception will occurs."""
    p = Person.create(**kw)
    p.save()


def create_a_person(**kw):
    """Create a Person instance with the given parameters, do not save
     and return it. You might want to use this function when you want to
     add more data and save it yourself manually."""
    return Person.create(**kw)


def search_person(field, value):
    """Search a record where the *field* satisfies the *value*. If the
    record no found, return None"""
    try:
        rslt = Person.select().where(getattr(Person, field) == value).get()
    except DoesNotExist:
        rslt = None

    return rslt


def edit_person_by_xuehao(xuehao, kw):
    """Modify one person's information via xuehao."""
    p = Person.select().where(getattr(Person, 'xuehao') == xuehao).get()
    for k in kw:
        setattr(p, k, kw[k])

    p.save()


def delete_person_by_xuehao(xuehao):
    p = Person.select().where(Person.xuehao == xuehao).get()
    p.delete_instance()


if __name__ == '__main__':
    info = {
        'xuehao': 'xh666',
        'open_id': 'id666'
    }

    print()
    print("add ")
    add_a_person(info)

    print()
    print("search")
    p = search_person('xuehao', info['xuehao'])
    p = search_person('open_id', info['open_id'])

    print()
    print('edit')
    edit_person_by_xuehao(info['xuehao'], {'open_id': 'id777'})
    p = search_person('xuehao', info['xuehao'])
    print('xuehao: ', p.xuehao, ' open_id:', p.open_id)

    print()
    print('delete')
    delete_person_by_xuehao(info['xuehao'])
    p = search_person('xuehao', info['xuehao'])

    print()
    print("All test pass")


